package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCommonForAdminService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwV2.dto.dto.childrenVisits.ChildrenVisitationPdfDTO;
import com.budwk.app.sqfwV2.enums.FileServiceConfigEnum;
import com.budwk.app.sqfwV2.service.childrenVisitation.ChildrenVisitationExcelService;
import com.budwk.app.sqfwV2.service.childrenVisitation.ChildrenVisitationService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: dfxy-community
 * @description: 观山湖区创业实体入户（后台管理）
 * @author: LJT
 * @create: 2024-04-26 08:33
 **/
@IocBean(name = "BaiYunQuChildVisitForAdminService")
@Slf4j
public class BaiYunQuChildVisitForAdminServiceImpl extends ChildrenVisitationExcelService implements SqfwCustomForAdminCommonService {

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysLogService sysLogService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private ChildrenVisitationService childrenVisitationService;

    @Inject
    private SysOssService sysOssService;

    @Inject
    private SqfwCommonForAdminService sqfwCommonForAdminService;

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("BaiYunQuChildVisitForAdminServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        // 查询流程pdf
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictSubInfoMaps(Arrays.asList(
                    "children_category_orphan",
                    "children_category_raising",
                    "children_category_behind",
                    "children_category_difficult",
                    "children_category_other",
                    "work_situation_in_school",
                    "work_situation_no_school"));
            sqfwCustomForAdminCommonVOList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                ChildrenVisitationPdfDTO enterDTO = JSONObject.parseObject(target.getParamData(), ChildrenVisitationPdfDTO.class);
                if (ObjectUtil.isNotEmpty(enterDTO)) {
                    String childrenType = enterDTO.getChildrenType();
                    if (StringUtils.isNotEmpty(childrenType)) {
                        target.setChildrenTypeName(dictCodesMap.get(childrenType));
                    }
                    String learningCondition = enterDTO.getLearningCondition();
                    if (StringUtils.isNotEmpty(learningCondition)) {
                        target.setLearningConditionName(dictCodesMap.get(learningCondition));
                    }
                }
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("BaiYunQuChildVisitForAdminServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int delete(String id) {
        Sqfw_formSummary_new sqfwFormSummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormSummaryNew == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        batchDeleteDataNew(SecurityUtil.getUserId(), sqfwFormSummaryNew);
        return 0;
    }

    @Override
    public int batchDelete(List<String> ids) {
        return sqfwCommonForAdminService.batchDelete(ids);
    }

    @Override
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        return 0;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }

        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            // 时间
            if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
                cnd.and(Sqfw_formSummary_new::getFillDate, ">=", communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()));
                cnd.and(Sqfw_formSummary_new::getFillDate, "<=", communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
            }
            cnd.and(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            bean.setFormSummaryNewIdList(Collections.emptyList());
        }
        return super.generateExcelForAdmin(excelConfigList, SecurityUtil.getUserId(), bean.getFormSummaryNewIdList());
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            String fileName = SupportBusinessTypeEnum.CHILDREN_VISITATION.getName() + ".docx";
            String filepath = "sqfwV2/childrenVisits/template/childrenVisitsRecordWord.docx";
            generateWordAndPdfUrlVO.setPdfUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filepath), fileName).getUrl());
            return generateWordAndPdfUrlVO;
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new GenerateWordAndPdfUrlVO();
            }
        }
        generateWordAndPdfUrlVO.setPdfUrl(generatePdfColl(bean.getFormSummaryNewIdList(), excelConfigList.get(0).getFileIdentity()));
        return generateWordAndPdfUrlVO;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(Sqfw_formSummary_new::getFillDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity())) {
            criSql.andLike(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup visitedName = Cnd.exps(new Static("param_data->>'visitedName' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup address = Cnd.exps(new Static("param_data->>'address' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup childrenType = Cnd.exps(new Static("param_data->>'childrenType' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup county = Cnd.exps(new Static("county like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup community = Cnd.exps(new Static("community like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("create_user_name like '%" + bean.getQueryAll() + "%'"));
            criSql.and(visitedName.or(address).or(childrenType).or(county).or(community).or(createUserName));
        }
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);

        // 被探访儿童姓名
        if (StringUtils.isNotBlank(bean.getCaseName())) {
            criSql.andEquals("param_data->>'visitedName'", bean.getCaseName());
        }
        // 现居住地址
        if (StringUtils.isNotBlank(bean.getAddress())) {
            criSql.andEquals("param_data->>'address'", bean.getAddress());
        }
        // 儿童类别
        if (StringUtils.isNotEmpty(bean.getChildrenType())) {
            criSql.andEquals("param_data->>'childrenType'", bean.getChildrenType());
        }
        // 学工情况
        if (StringUtils.isNotEmpty(bean.getLearningCondition())) {
            criSql.andEquals("param_data->>'learningCondition'", bean.getLearningCondition());
        }
        // 探访人
        if (StringUtils.isNotEmpty(bean.getCreateUserName())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        // 监护人
        if (StringUtils.isNotEmpty(bean.getName())) {
            criSql.andEquals("param_data->'guardianInfos'->0->>'name'", bean.getName());
        }
        // 监护人电话
        if (StringUtils.isNotEmpty(bean.getPhone())) {
            criSql.andEquals("param_data->'guardianInfos'->0->>'phone'", bean.getPhone());
        }
        return cri;
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<CheckDataForAdminVO>();
            }
        }
        List<CheckDataForAdminVO> checkDataForAdminVOList = new ArrayList<CheckDataForAdminVO>();
        List<FileServiceConfigEnum> configEnums = FileServiceConfigEnum.findByFillType(SupportBusinessTypeEnum.CHILDREN_VISITATION.getName(), null);
        for (FileServiceConfigEnum item : configEnums) {
            CheckDataForAdminVO checkDataForAdminVO = new CheckDataForAdminVO();
            checkDataForAdminVO.setFileIdentity(String.valueOf(item.getCode()));
            checkDataForAdminVO.setCreateConditionFlag(false);
            checkDataForAdminVO.setFileName(item.getFileName());
            if (item.getFilePath().endsWith("xlsx")) {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName());
            } else {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".pdf");
            }
            checkDataForAdminVOList.add(checkDataForAdminVO);
        }
        if (bean.getFormSummaryNewIdList().size() <= 0) {
            return checkDataForAdminVOList;
        }
        for (CheckDataForAdminVO item : checkDataForAdminVOList) {
            item.setCreateConditionFlag(true);
        }
        return checkDataForAdminVOList;
    }

    @Override
    public void reGeneratePdf(String id) {
        childrenVisitationService.reGeneratePDF(id);
    }

    /**
     * 生成pdf合集
     *
     * @return
     */
    private String generatePdfColl(List<String> ids, String code) {
        String url = "";
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(Cnd.where(Sqfw_formSummary_new::getId, "IN", ids)
                .and("type", "=", SupportBusinessTypeEnum.CHILDREN_VISITATION.getName()));
        if (CollectionUtil.isNotEmpty(formSummaryList)) {
            List<String> summaryIdS = formSummaryList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
            List<Sqfw_completeflow> completeflow = sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "IN", summaryIdS)
                    .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                    .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
            if (CollectionUtil.isNotEmpty(completeflow)) {
                List<String> pdfPathList = completeflow.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
                url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, FileServiceConfigEnum.CA.getFileName());
            }
        }
        return url;
    }

    /**
     * 批量删除
     *
     * @param userId
     * @param data
     */
    private void batchDeleteDataNew(String userId, Sqfw_formSummary_new data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.customservice.GuanShanHuEntGuaranteeForAdminServiceImpl.batchDeleteDataNew",
                "com.budwk.app.sqfw.controllers.admin.GuanShanHuEntGuaranteeForAdminServiceImpl.batchDelete");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }
}
